import React, { Component } from "react";
import moment from 'moment'
import {
    BasicLayout,
    BasicLayoutSearch,
} from "../../../components/BasicLayout";
import {
    BasicPagination,
    compareNum,
    TableCustomize,
    openSuccessModal,
    openModalMessage,
    compareString,
    isInvalidObject,
} from "../../../components/TableCustomize";
import { Button, Drawer, Alert, Badge, Icon, Modal, DatePicker, Select } from "antd";
import SearchForm from "./SearchForm";
import * as ProduceDispatchService from "../../../axios/ProduceDispatch";
import * as GetSuooliseService from "../../../axios/GetSuoolise";
import img from "../../../assets/img/flame.png";
import { withPermission } from '../../../components/withpermission'

const { Option } = Select

export default class ProduceDispatch extends Component {
    state = {
        dataSource: [],
        searchItem: {},
        advanced: false,
        pageNum: 1,
        pageSize: 100,
        total: 0,
        columns: [
            {
                title: "序号",
                dataIndex: "serialNumber",
                width: 60,
                render: (text, record, index) => (
                    <div style={{ display: "flex" }}>
                        <div>
                            {(this.state.pageNum - 1) * this.state.pageSize + index + 1}
                        </div>
                        {record.isRush === 1 || record.isRush === "1" ? (
                            <img src={img} style={{ width: "18px", height: "18px" }} />
                        ) : null}
                    </div>
                ),
            },
            {
                title: "批号",
                dataIndex: "batchNo",
                sorter: (a, b) => compareString(a.batchNo, b.batchNo),
                width: 100,
            },
            {
                title: "装配部门",
                dataIndex: "department",
                sorter: (a, b) => compareString(a.department, b.department),
                width: 200,
            },
            {
                title: "机型",
                dataIndex: "model",
                sorter: (a, b) => compareString(a.model, b.model),
                width: 100,
            },
            {
                title: "导入时间",
                dataIndex: "importTime",
                sorter: (a, b) => new Date(a.importTime).getTime() - new Date(b.importTime).getTime(),
                width: 100,
            },
            {
                title: "装配班组",
                dataIndex: "assemblyGroup",
                sorter: (a, b) => compareString(a.assemblyGroup, b.assemblyGroup),
                width: 150,
                render: (text, record) => {
                    const { groupList } = this.state
                    return <Select allowClear placeholder='请选择装配班组' onChange={this.onChangeGroup} style={{ width: '100%' }} defaultValue={text ? text : undefined}>
                        {
                            groupList && groupList.map((value, index) =>
                                <Option key={value.groupCode}>{value.groupName}</Option>
                            )
                        }
                    </Select>
                }
            },
            {
                title: "机位",
                dataIndex: "seat",
                sorter: (a, b) => compareString(a.seat, b.seat),
                width: 150,
                render: (text, record) => {
                    const { seatList } = this.state
                    return <Select allowClear placeholder='请选择机位' onChange={this.onChangeSeat} style={{ width: '100%' }} defaultValue={text ? text : undefined}>
                        {
                            seatList && seatList.map((value, index) =>
                                <Option key={value.code}>{value.seatList}</Option>
                            )
                        }
                    </Select>
                }
            },
            {
                title: "需求时间",
                dataIndex: "requestTime",
                sorter: (a, b) => new Date(a.requestTime).getTime() - new Date(b.requestTime).getTime(),
                width: 150,
                render: (text, record) => {
                    return <DatePicker placeholder="请选择需求时间" onChange={this.onChangeDate} style={{ width: '100%' }} defaultValue={text ? moment(new Date(text)) : undefined} />
                }
            },
            {
                title: "是否发布",
                dataIndex: "isRelease",
                sorter: (a, b) => compareNum(a.isRelease, b.isRelease),
                width: 100,
                render: (text, record) => (
                    <div>
                        {text == "0" ? (
                            <Badge
                                status="default"
                                text={<span style={{ color: "#d9d9d9" }}>待发布</span>}
                            />
                        ) : text == "1" ? (
                            <Badge
                                color="#1890ff"
                                text={<span style={{ color: "#1890ff" }}>已发布</span>}
                            />
                        ) : (
                            text
                        )}
                    </div>
                ),
            },
            {
                title: "操作",
                dataIndex: "opts",
                width: 100,
                render: (text, record, index) => {
                    return <a onClick={() => { this.release(record) }}>发布</a>
                }
            },
            { dataIndex: "" },
        ],
        selectedRowKeys: [],
        selectedRows: [],
        loading: false,
        seatList: [],  // 机位
        groupList: [],  // 班组
        formData: {},
    };
    componentDidMount() {
        const { searchItem } = this.state;
        this.setState({ searchItem, }, () => { this.fetch(); this.getList() });
    }
    getList = () => {
        GetSuooliseService.seatList().then((value) => {
            if (value.data.code !== 200) {
                return
            }
            let seatList = value.data.data, data = []
            for (const key in seatList) {
                data.push({ code: key, seatList: seatList[key] })
            }
            this.setState({
                seatList: data
            })
        })
        GetSuooliseService.groupList().then((value) => {
            if (value.data.code !== 200) {
                return
            }
            this.setState({
                groupList: value.data.data
            })
        })
    }
    // 选择班组
    onChangeGroup = (value) => {
        console.log(value, 'onChangeGroup');
        let formData = this.state.formData
        // formData.assemblyGroup = value
        formData.assemblyGroup = value ? value : ''
        this.setState({ formData })
    }
    // 选择机位
    onChangeSeat = (value) => {
        console.log(value, 'onChangeSeat');
        let formData = this.state.formData
        // formData.seat = value
        formData.seat = value ? value : ''
        this.setState({ formData })
    }
    // 选择需求日期
    onChangeDate = (value) => {
        console.log(value, 'onChangeDate');
        let formData = this.state.formData
        // formData.requestTime = new Date(value)
        // formData.requestTime = value ? new Date(value) : "1970-01-01T00:00:00.000Z"
        formData.requestTime = value ? new Date(value) : null
        this.setState({ formData })
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        this.setState({ loading: true });
        const { searchItem } = this.state;
        searchItem.pageNum = pageNum;
        searchItem.pageSize = pageSize;
        // console.log('这是什么', searchItem);
        ProduceDispatchService.batchNumberList(searchItem)
            .then((res) => {
                // console.log(res);
                if (res.data.code !== 200) {
                    openModalMessage("warning", res.data.msg);
                    return;
                }
                this.setState({
                    dataSource: res.data.data,
                    total: res.data.total,
                    pageNum,
                    pageSize,
                    selectedRowKeys: [],
                    selectedRows: [],
                    loading: false,
                });
            })
            .catch((err) => {
                openModalMessage("error", err.message);
            });
    };
    // 高级查询
    advanced = () => {
        this.setState({ advanced: !this.state.advanced });
    };
    handleSearch = (value) => {
        const { pageNum, pageSize } = this.state;
        this.setState({ searchItem: value }, () => {
            this.fetch();
        });
    };
    // 发布
    release = (record) => {
        console.log(record, '发布');
        let that = this
        Modal.confirm({
            title: "确认是否发布",
            // icon: <Icon type="close-circle" />,
            okText: "确认",
            cancelText: "关闭",
            onOk: async () => {
                console.log({ ...record, ...that.state.formData });
                await ProduceDispatchService.batchPublishList({ ...record, ...that.state.formData })
                    .then((res) => {
                        console.log(res);
                        if (res.data.code !== 200) {
                            openModalMessage("warning", res.data.msg);
                            return;
                        }
                        openSuccessModal(res.data.msg)
                        that.fetch()
                    })
                    .catch((err) => {
                        openModalMessage("error", err.message);
                    });
            },
            onCancel() {
            },
        });
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({ searchItem: {} }, () => {
            this.fetch();
        });
    };
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    render() {
        const {
            advanced,
            loading,
            dataSource,
            columns,
            selectedRowKeys,
            pageSize,
            pageNum,
            total,
            groupList, seatList
        } = this.state;
        const rowSelection = {
            columnWidth: 40,
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                const keys = [...this.state.selectedRowKeys];
                const rows = [...this.state.selectedRows];
                if (selected) {
                    changeRows.forEach((row) => {
                        if (isInvalidObject(keys.find((key) => key === row.id))) {
                            keys.push(row.id);
                            rows.push(row);
                        }
                    });
                } else {
                    changeRows.forEach((row) => {
                        keys.splice(keys.indexOf(row.id), 1);
                        rows.splice(rows.indexOf(row), 1);
                    });
                }
                this.setState({ selectedRows: rows, selectedRowKeys: keys });
            },
        };

        console.log(groupList, seatList, '------------');
        return (
            <div>
                <BasicLayoutSearch>
                    <SearchForm
                        onSearch={this.handleSearch}
                        onClick={this.advanced}
                        advanced={advanced} groupList={groupList} seatList={seatList}
                        resetForm={this.resetForm}
                        ref={(node) => (this.formSearch = node)}
                    ></SearchForm>
                </BasicLayoutSearch>
                {/* <Alert
                    message={
                        <div>已选择 <span>{selectedRowKeys.length}</span> 项{" "}<a onClick={() => this.setState({ selectedRowKeys: [], selectedRows: [] })}>清除</a>{" "}</div>
                    }
                    type="info"
                    showIcon
                    style={{ width: "99%", margin: "auto" }}
                /> */}
                <BasicLayout
                    name={`生产派工`}
                    icon="table"
                    buttons={[
                        // <RefreshButton key={1} onClick={() => this.renewal()} icon='sync' />,
                        // <FBButton key={2} onClick={() => this.issue()} icon='alert' />,
                        // <JJButton key={3} onClick={() => this.urgent()} icon='rocket' />,
                    ]}
                >
                    <TableCustomize
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        rowClassName={(record, index) => {
                            return [
                                "editable-row",
                                index % 2 === 0 ? "editable-row" : "editable-row12",
                            ];
                        }}
                        // rowSelection={rowSelection}
                        scroll={{ x: true, y: 450 }}
                    />
                    <BasicPagination
                        pageNum={pageNum}
                        pageSize={pageSize}
                        total={total}
                        loadData={this.fetch}
                    />
                </BasicLayout>

            </div>
        );
    }
}